package blacknWhite.MarketSalesMonitor;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import blacknWhite.Libraries.AppDatabase;
import blacknWhite.Libraries.CheckoutLibrary;
import blacknWhite.Libraries.MarketLibrary;
import blacknWhite.Libraries.Utils;
import blacknWhite.Libraries.AppDatabase.AppCommentsColumns;
import blacknWhite.Libraries.AppDatabase.OrdersColumns;

import com.nullwire.trace.ExceptionHandler;

public class HomeActivity extends Activity {

	static Lock lock = new ReentrantLock();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ExceptionHandler.register(this, "http://blacknwhitedev.com/stack-trace");
		if (Utils.handler == null)
			Utils.handler = new Handler();

		try {
			this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

			setContentView(R.layout.activity_home);

			Eula.show(this);

			DisplaySummaryToggler(0);

			// Start service
			startService(MarketSalesMonitorService.GetIntent());
		} catch (Throwable e) {
			Utils.LogException(e);
		}

	}

	int displayingCurrentSummaryId = 0;

	private void DisplaySummaryToggler(int summaryId) {
		Date now = new Date();

		if (summaryId == 0)
			DisplaySummary(now, this.getString(R.string.titleTodaySummary));
		else if (summaryId == 1) {
			long yesterdayMills = now.getTime() - (24 * 60 * 60 * 1000);
			Date yesterday = new Date(yesterdayMills);
			DisplaySummary(yesterday, this
					.getString(R.string.titleYesterdaySummary));
		}

		summaryId++;
		if (summaryId > 1)
			summaryId = 0;
		
		displayingCurrentSummaryId = summaryId;
	}

	// Timer summaryTimer = new Timer();
	// int displayingSummaryId = 0;

	private void DisplaySummary(final Date day, final String title) {
		final AppDatabase mOpenHelper = new AppDatabase(this);

		new Thread(new Runnable() {

			public void run() {
				long totalDailyOrdersCount = 0;
				float totalDailyOrdersMoney = 0;
				float totalSumRatings = 0;
				int totalDailyComments = 0;
				// String currency = "";

				SQLiteDatabase db = null;
				Cursor cursorOrders = null;
				Cursor cursorComments = null;

				if (!lock.tryLock())
					return;

				try {

					Date nowDate = day;

					db = mOpenHelper.getReadableDatabase();

					// Orders summary
					cursorOrders = db.query(AppDatabase.Tables.ORDERS, null,
							null, null, null, null, OrdersColumns.SALE_DATE
									+ " ASC");

					if (cursorOrders.moveToFirst()) {
						do {
							// Get date
							Long saleDateLong = cursorOrders
									.getLong(OrdersColumns.SALE_DATE_ID);
							Date saleDate = new Date(saleDateLong);

							if (saleDate.getDate() != nowDate.getDate()
									|| saleDate.getMonth() != nowDate
											.getMonth()
									|| saleDate.getYear() != nowDate.getYear())
								continue;

							Double total = cursorOrders
									.getDouble(OrdersColumns.TOTAL_ID);
							String status = cursorOrders
									.getString(OrdersColumns.STATUS_ID);
							if (status == null)
								status = "";

							if (status.contentEquals("CANCELLED"))
								continue;
							if (status.contentEquals("CANCELLED_BY_GOOGLE"))
								continue;
							if (status.contentEquals("PAYMENT_DECLINED"))
								continue;

							totalDailyOrdersCount++;
							totalDailyOrdersMoney += total;
						} while (cursorOrders.moveToNext());
					}
					cursorOrders.close();

					// Comments summary
					cursorComments = db.query(AppDatabase.Tables.APP_COMMENTS,
							null, null, null, null, null,
							AppCommentsColumns.CREATION_TIME + " ASC");

					if (cursorComments.moveToFirst()) {
						do {
							// Get date
							Long creationTimeLong = cursorComments
									.getLong(AppCommentsColumns.CREATION_TIME_ID);
							Date creationTime = new Date(creationTimeLong);

							if (creationTime.getDate() != nowDate.getDate()
									|| creationTime.getMonth() != nowDate
											.getMonth()
									|| creationTime.getYear() != nowDate
											.getYear())
								continue;

							float rating = cursorComments
									.getFloat(AppCommentsColumns.RATING_ID);
							totalSumRatings = totalSumRatings + rating;
							totalDailyComments++;
						} while (cursorComments.moveToNext());
					}
					cursorComments.close();

				} catch (Throwable ex) {
					Utils.LogException(ex);
				} finally {
					lock.unlock();
				}

				// Define messages to display
				NumberFormat currencyFormatter = NumberFormat
						.getCurrencyInstance();
				String totalCurrency = currencyFormatter
						.format(totalDailyOrdersMoney);
				final String salesLine = "Sales: "
						+ String.valueOf(totalDailyOrdersCount) + " orders / "
						+ totalCurrency;

				String commentsLineTemp = "";
				if (totalDailyComments > 0) {
					String ratingFormatted = String.format("%.1f",
							totalSumRatings / totalDailyComments);
					commentsLineTemp = String.valueOf(totalDailyComments)
							+ " Comments, " + ratingFormatted + " Stars ";
				} else
					commentsLineTemp = String.valueOf(totalDailyComments)
							+ " Comments";
				final String commentsLine = commentsLineTemp;

				// show results in UI thread
				Utils.handler.post(new Runnable() {
					public void run() {
						displayResultsSummary(salesLine, commentsLine, title);
					}
				});
			}

		}).start();
	}

	private void displayResultsSummary(final String salesLine,
			final String commentsLine, final String title) {
		try {
			View summaryView = getLayoutInflater().inflate(
					R.layout.home_summary, null);

			TextView homeSummaryTitle = (TextView) summaryView
					.findViewById(R.id.home_summaryTitle);
			TextView homeSummary1 = (TextView) summaryView
					.findViewById(R.id.home_summary1);
			TextView homeSummary2 = (TextView) summaryView
					.findViewById(R.id.home_summary2);

			homeSummaryTitle.setText(title);
			homeSummary1.setText(salesLine);
			homeSummary2.setText(commentsLine);

			final LinearLayout nowPlayingLoading = (LinearLayout) HomeActivity.this
					.findViewById(R.id.now_playing_loading);
			nowPlayingLoading.setVisibility(View.GONE);
			ViewGroup homeRoot = (ViewGroup) findViewById(R.id.home_root);

			removeSummaryFrame();
			homeRoot.addView(summaryView, new LayoutParams(
					LayoutParams.FILL_PARENT, (int) getResources()
							.getDimension(R.dimen.now_playing_height)));
		} catch (NotFoundException e) {
			Utils.LogException(e);
		}
	}

	public void onPreferenesClick(View v) {
		// Launch
		startActivity(new Intent(this, PreferencesActivity.class));
	}

	public void onOrdersClick(View v) {
		// Launch
		startActivity(new Intent(this, OrdersActivity.class));

	}

	public void onCommentsClick(View v) throws IllegalStateException, IOException {
		
		// Launch
		startActivity(new Intent(this, CommentsActivity.class));
	}

	public void onSearchClick(View v) {
		// Launch
		// startActivity(new Intent(this, ScheduleActivity.class));
	}

	public void onAppIconClick(View v) {
		DisplaySummaryToggler(displayingCurrentSummaryId);
	}

	public void onRefreshClick(View v) {
		// Launch
		final LinearLayout nowPlayingLoading = (LinearLayout) findViewById(R.id.now_playing_loading);
		removeSummaryFrame();

		ArrayAdapter<View> adapter = new ArrayAdapter<View>(this, 0) {
			@Override
			public void notifyDataSetChanged() {
				// TODO Auto-generated method stub
				super.notifyDataSetChanged();
				DisplaySummaryToggler(0);
			}

		};

		try {
			CheckoutLibrary.refreshOrders(nowPlayingLoading, adapter, this);
			MarketLibrary.refreshComments(nowPlayingLoading, adapter, this);
		} catch (Throwable e) {
			Utils.LogException(e);
		}
	}

	private void removeSummaryFrame() {
		ViewGroup homeRoot = (ViewGroup) findViewById(R.id.home_root);
		LinearLayout summaryLayout = (LinearLayout) homeRoot
				.findViewById(R.id.home_summary_layout);
		if (homeRoot != null && summaryLayout != null)
			homeRoot.removeView(summaryLayout);
	}

}